<template>
  <div class="admin" v-loading="loadingUser">
    <div class="admin-title">{{ t("memberProfile.title") }}</div>

    <el-tabs v-model="activeTab" class="profile-tabs" @tab-change="handleTabChange">
      <el-tab-pane v-for="tab in tabList" :key="tab.name" :label="tab.label" :name="tab.name" />
    </el-tabs>

    <div v-if="activeTab === 'personal'" class="personal-info-content">
      <el-row :gutter="20">
        <el-col :span="18">
          <div class="info-content">
            <div class="info-section">
              <div class="info-item">
                <span class="label">{{ t("memberProfile.lastNameEn") }}:</span>
                <span class="value">{{ displayValue(userInfo.nameSur) }}</span>
              </div>
              <div class="info-item">
                <span class="label">{{ t("memberProfile.firstNameEn") }}:</span>
                <span class="value">{{ displayValue(userInfo.nickname) }}</span>
              </div>
              <div class="info-item">
                <span class="label">{{ t("memberProfile.nameCn") }}:</span>
                <span class="value">{{ displayValue(userInfo.nameC) }}</span>
              </div>
              <div class="info-item">
                <span class="label">{{ t("memberProfile.gender") }}:</span>
                <span class="value">{{ formatSex(userInfo.sex) }}</span>
              </div>
              <div class="info-item">
                <span class="label">{{ t("memberProfile.birthday") }}:</span>
                <span class="value">{{ displayValue(userInfo.birthDate) }}</span>
              </div>
              <div class="info-item">
                <span class="label">{{ t("memberProfile.nationality") }}:</span>
                <span class="value">{{ displayValue(userInfo.country) }}</span>
              </div>
              <div class="info-item">
                <span class="label">{{ t("memberProfile.ethnicity") }}:</span>
                <span class="value">{{ displayValue(userInfo.nationality) }}</span>
              </div>
              <div class="info-item">
                <span class="label">{{ t("memberProfile.hukou") }}:</span>
                <span class="value">{{ displayValue(userInfo.household) }}</span>
              </div>
              <div class="info-item">
                <span class="label">{{ t("memberProfile.education") }}:</span>
                <span class="value">{{ displayValue(userInfo.qualification) }}</span>
              </div>
            </div>

            <el-divider />

            <div class="info-section">
              <div class="info-item editable">
                <span class="label">{{ t("memberProfile.phone") }}:</span>
                <span class="value">{{ displayValue(userInfo.phone) }}</span>
                <el-button type="text" class="modify-btn" @click="openPhoneForm">
                  {{ t("memberProfile.modify") }}
                </el-button>
              </div>
              <div class="info-item editable">
                <span class="label">{{ t("memberProfile.email") }}:</span>
                <span class="value">{{ displayValue(userInfo.email) }}</span>
                <el-button type="text" class="modify-btn" @click="showEmailForm = true">
                  {{ t("memberProfile.modify") }}
                </el-button>
              </div>
              <div class="info-item editable">
                <span class="label">{{ t("memberProfile.address") }}:</span>
                <span class="value">{{ displayValue(userInfo.address) }}</span>
                <el-button type="text" class="modify-btn" @click="showAddressForm = true">
                  {{ t("memberProfile.modify") }}
                </el-button>
              </div>
            </div>

            <el-divider />

            <div class="info-section">
              <div class="info-item">
                <span class="label">{{ t("memberProfile.idType") }}:</span>
                <span class="value">{{ displayValue(userInfo.certificateType) }}</span>
              </div>
              <div class="info-item">
                <span class="label">{{ t("memberProfile.idNumber") }}:</span>
                <span class="value">{{ displayValue(userInfo.certificateNo) }}</span>
              </div>
              <div class="info-item">
                <span class="label">{{ t("memberProfile.idPhotos") }}:</span>
                <div class="id-photos">
                  <div class="photo-placeholder">
                    <el-image v-if="userInfo.photoFront" :src="userInfo.photoFront" fit="cover" class="id-image"
                      :alt="t('memberProfile.idPhotoFront')" />
                    <div v-else class="mountain-bg">
                      <div class="sun"></div>
                    </div>
                  </div>
                  <div class="photo-placeholder">
                    <el-image v-if="userInfo.photoReverse" :src="userInfo.photoReverse" fit="cover" class="id-image"
                      :alt="t('memberProfile.idPhotoBack')" />
                    <div v-else class="mountain-bg">
                      <div class="sun"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="avatar-section">
            <div class="avatar-placeholder">
              <el-image v-if="userInfo.profileUrl" :src="userInfo.profileUrl" fit="cover" class="avatar-image"
                :alt="t('memberProfile.avatarAlt')" />
              <div v-else class="mountain-bg">
                <div class="sun"></div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <div v-if="activeTab === 'registration'" class="registration-info-content">
      <div class="registration-list">
        <!-- 注册机构 -->
        <div class="registration-item">
          <span class="label">{{ t("memberProfile.institution") }}:</span>
          <span class="value">{{ displayValue(registrationInfo.associationName) }}</span>
        </div>
        <!-- 生涯状态 -->
        <div class="registration-item">
          <span class="label">{{ t("memberProfile.careerStatus") }}:</span>
          <span class="value">
            <el-button type="text"
              :class="{ active: registrationInfo.resignStatusCode === '0' || registrationInfo.resignStatusCode === '3' }"
              :disabled="updateLoading.career" @click="updateCareerStatus('3')">
              {{ t("memberProfile.careerActive") }}
            </el-button>
            <span>/</span>
            <el-button type="text" :class="{ active: registrationInfo.resignStatusCode === '1' }"
              :disabled="updateLoading.career" @click="updateCareerStatus('1')">
              {{ t("memberProfile.careerRetired") }}
            </el-button>
          </span>
        </div>
        <!-- 身份类型 -->
        <div class="registration-item">
          <span class="label">{{ t("memberProfile.identityType") }}:</span>
          <span class="value">{{ formatUserType(registrationInfo.userType) }}</span>
        </div>
        <!-- 注册项目 -->
        <div class="registration-item">
          <span class="label">{{ t("memberProfile.registeredItem") }}:</span>
          <span class="value">{{ displayValue(registrationInfo.registerProject) }}</span>
        </div>
        <!-- 会员编码 -->
        <div class="registration-item">
          <span class="label">{{ t("memberProfile.memberCode") }}:</span>
          <span class="value">{{ displayValue(registrationInfo.membershipCode) }}</span>
        </div>
        <!-- 职业等级 -->
        <div class="registration-item">
          <span class="label">{{ t("memberProfile.professionalLevel") }}:</span>
          <span class="value">{{ displayValue(registrationInfo.occupationalLevel) }}</span>
        </div>
        <!-- 首次注册日期 -->
        <div class="registration-item">
          <span class="label">{{ t("memberProfile.firstRegistrationDate") }}:</span>
          <span class="value">{{ displayValue(registrationInfo.firstTime) }}</span>
        </div>
        <!-- 最近认证年度 -->
        <div class="registration-item">
          <span class="label">{{ t("memberProfile.recentCertificationYear") }}:</span>
          <span class="value">{{ displayValue(registrationInfo.registrationTime) }}</span>
        </div>
        <!-- 认证状态 -->
        <div class="registration-item">
          <span class="label">{{ t("memberProfile.certificationStatus") }}:</span>
          <span class="value">{{ formatRegistrationStatus(registrationInfo.registrationCode) }}</span>
        </div>
        <!-- 所在属会 -->
        <div class="registration-item">
          <span class="label">{{ t("memberProfile.affiliatedClub") }}:</span>
          <span class="value">{{ displayValue(registrationInfo.associationName) }}</span>
        </div>
        <!-- 属会编码 -->
        <div class="registration-item">
          <span class="label">{{ t("memberProfile.clubCode") }}:</span>
          <span class="value">{{ displayValue(registrationInfo.associationCode) }}</span>
        </div>
        <!-- 备注 -->
        <div class="registration-item">
          <span class="label">{{ t("memberProfile.remarks") }}:</span>
          <span class="value">{{ displayValue(registrationInfo.notes) }}</span>
        </div>
      </div>
    </div>

    <el-dialog v-model="showPhoneForm" :title="t('memberProfile.editPhoneTitle')" width="400px">
      <el-form :model="phoneForm" :rules="phoneRules" ref="phoneFormRef">
        <el-form-item prop="areaCode">
          <el-select v-model="phoneForm.areaCode" :placeholder="t('memberProfile.selectAreaCode')" style="width: 100%;">
            <el-option v-for="item in phoneAreaOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="newPhone">
          <el-input v-model="phoneForm.newPhone" :placeholder="t('memberProfile.newPhonePlaceholder')" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelPhone">{{ t("memberProfile.cancel") }}</el-button>
        <el-button type="primary" :loading="updateLoading.phone" @click="savePhone">
          {{ t("memberProfile.save") }}
        </el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showEmailForm" :title="t('memberProfile.editEmailTitle')" width="400px">
      <el-form :model="emailForm" :rules="emailRules" ref="emailFormRef">
        <el-form-item prop="newEmail">
          <el-input v-model="emailForm.newEmail" :placeholder="t('memberProfile.newEmailPlaceholder')" />
        </el-form-item>
        <el-form-item prop="confirmEmail">
          <el-input v-model="emailForm.confirmEmail" :placeholder="t('memberProfile.confirmEmailPlaceholder')" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelEmail">{{ t("memberProfile.cancel") }}</el-button>
        <el-button type="primary" :loading="updateLoading.email" @click="saveEmail">
          {{ t("memberProfile.save") }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 修改地址 -->
    <el-dialog v-model="showAddressForm" :title="t('memberProfile.editAddressTitle')" width="450px">
      <el-form :model="addressForm" :rules="addressRules" ref="addressFormRef" label-width="0">
        <div class="address-row">
          <el-form-item class="address-select-item" prop="province">
            <el-select v-model="addressForm.province" :placeholder="t('memberProfile.selectProvince')"
              class="address-select">
              <el-option v-for="item in provinceOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <div class="address-gap"></div>
          <el-form-item class="address-select-item" prop="city">
            <el-select v-model="addressForm.city" :placeholder="t('memberProfile.selectCity')" class="address-select">
              <el-option v-for="item in cityOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item prop="detailAddress" style="width: 100%;margin-top: 12px;">
          <el-input v-model="addressForm.detailAddress" :placeholder="t('memberProfile.detailAddressPlaceholder')" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelAddress">{{ t("memberProfile.cancel") }}</el-button>
        <el-button type="primary" :loading="updateLoading.address" @click="saveAddress">
          {{ t("memberProfile.save") }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, reactive, ref, watch } from "vue";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import { GetPlatformUserDetail, UpdatePlatformUser } from "~/apis/admin";
import provinceCityData from "~/assets/province.json";
import { userStore } from "~/composables/store/modules/user";
import { formatUTCToLocalDate } from "~/utils/utils";

definePageMeta({
  title: "会员资料",
  en_title: "Member profile",
  zh_hk_title: "會員資料",
  ssr: true,
  isTokenCheck: true,
});

const { t } = useI18n();

const activeTab = ref("personal");
const loadingUser = ref(false);
const userDetail = ref(null);

const tabList = computed(() => [
  { label: t("memberProfile.personalTab"), name: "personal" },
  { label: t("memberProfile.registrationTab"), name: "registration" },
]);

const placeholder = computed(() => t("memberProfile.emptyPlaceholder"));

const userInfo = reactive({
  nameSur: "",
  nickname: "",
  nameC: "",
  sex: null,
  birthDate: "",
  country: "",
  nationality: "",
  household: "",
  qualification: "",
  phone: "",
  email: "",
  address: "",
  certificateType: "",
  certificateNo: "",
  photoFront: "",
  photoReverse: "",
  profileUrl: "",
  areaCode: "",
  mobile: "",
});

const registrationInfo = reactive({
  associationName: "",
  userType: null,
  registerProject: "",
  membershipCode: "",
  occupationalLevel: "",
  firstTime: "",
  registrationTime: "",
  registrationCode: null,
  associationCode: "",
  notes: "",
  resignStatusCode: null,
});

const showPhoneForm = ref(false);
const showEmailForm = ref(false);
const showAddressForm = ref(false);
const updateLoading = reactive({
  phone: false,
  email: false,
  address: false,
  career: false,
});

const phoneFormRef = ref();
const emailFormRef = ref();
const addressFormRef = ref();

const phoneForm = reactive({
  areaCode: "",
  newPhone: "",
});

const emailForm = reactive({
  newEmail: "",
  confirmEmail: "",
});

const addressForm = reactive({
  province: "",
  city: "",
  detailAddress: "",
});

const provinceOptions = computed(() => {
  const keys = Object.keys(provinceCityData || {});
  return keys.map((name) => ({ label: name, value: name }));
});

const cityOptions = computed(() => {
  const cities = provinceCityData[addressForm.province] || [];
  return cities.map((name) => ({ label: name, value: name }));
});

const phoneAreaOptions = computed(() => [
  { value: "86", label: `${t("memberProfile.areaCodeMainland")} (+86)` },
  { value: "852", label: `${t("memberProfile.areaCodeHongKong")} (+852)` },
]);

const normalizeAreaCode = (code) => {
  if (!code) return "";
  return code.toString().replace("+", "").trim();
};

const getDefaultAreaCode = () => normalizeAreaCode(userInfo.areaCode) || "86";

const activeAreaCode = computed(() => {
  const current = normalizeAreaCode(phoneForm.areaCode || userInfo.areaCode || "86");
  return current || "86";
});

const phoneRules = computed(() => {
  const areaCode = activeAreaCode.value;
  const isHK = areaCode === "852";
  const pattern = isHK ? /^[5-9]\d{7}$/ : /^1\d{10}$/;
  return {
    areaCode: [
      { required: true, message: t("memberProfile.areaCodeRequired"), trigger: "change" },
    ],
    newPhone: [
      { required: true, message: t("memberProfile.newPhoneRequired"), trigger: "blur" },
      {
        pattern,
        message: isHK ? t("memberProfile.hkPhoneFormatError") : t("memberProfile.cnPhoneFormatError"),
        trigger: "blur",
      },
    ],
  };
});

const emailRules = computed(() => ({
  newEmail: [
    { required: true, message: t("memberProfile.newEmailRequired"), trigger: "blur" },
    { type: "email", message: t("memberProfile.emailFormatError"), trigger: "blur" },
  ],
  confirmEmail: [
    { required: true, message: t("memberProfile.confirmEmailRequired"), trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        if (value !== emailForm.newEmail) {
          callback(new Error(t("memberProfile.emailNotMatch")));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
}));

const addressRules = computed(() => ({
  province: [
    { required: true, message: t("memberProfile.provinceRequired"), trigger: "change" },
  ],
  city: [
    { required: true, message: t("memberProfile.cityRequired"), trigger: "change" },
  ],
  detailAddress: [
    { required: true, message: t("memberProfile.detailAddressRequired"), trigger: "blur" },
  ],
}));

const store = userStore();
const { user } = storeToRefs(store);

const displayValue = (value) => {
  if (value === undefined || value === null || value === "") {
    return placeholder.value;
  }
  return value;
};

const formatPhone = (mobile, areaCode) => {
  if (!mobile) return "";
  const trimmedArea = areaCode ? areaCode.toString().trim() : "";
  const prefixNumber = trimmedArea
    ? trimmedArea.startsWith("+")
      ? trimmedArea
      : `+${trimmedArea}`
    : "";
  const prefix = prefixNumber ? `${prefixNumber} ` : "";
  return `${prefix}${mobile}`;
};

const formatSex = (sex) => {
  const value = sex === undefined || sex === null ? "" : String(sex);
  if (value === "1") return t("memberProfile.male");
  if (value === "0") return t("memberProfile.female");
  if (value === "2") return t("memberProfile.secret");
  return placeholder.value;
};

const formatUserType = (userType) => {
  if (userType === undefined || userType === null || userType === "") {
    return placeholder.value;
  }
  const map = {
    "0": t("memberProfile.userType.merchantAdmin"),
    "1": t("memberProfile.userType.merchantStaff"),
    "2": t("memberProfile.userType.associationAccount"),
    "3": t("memberProfile.userType.coach"),
    "4": t("memberProfile.userType.teacher"),
    "5": t("memberProfile.userType.member"),
    "6": t("memberProfile.userType.referee"),
    "7": t("memberProfile.userType.committee"),
    "8": t("memberProfile.userType.platformUser"),
    "9": t("memberProfile.userType.athlete"),
    volunteer: t("memberProfile.userType.volunteer"),
  };
  return map[String(userType)] || placeholder.value;
};

const formatRegistrationStatus = (status) => {
  if (status === undefined || status === null || status === "") {
    return placeholder.value;
  }
  const map = {
    "0": t("memberProfile.statusTraining"),
    "1": t("memberProfile.statusRetired"),
    "2": t("memberProfile.statusRemoved"),
    "3": t("memberProfile.statusTraining"),
  };
  return map[String(status)] || placeholder.value;
};

const fillUserInfo = (detail) => {
  userInfo.nameSur = detail.nameSur || "";
  userInfo.nickname = detail.nickname || "";
  userInfo.nameC = detail.nameC || "";
  userInfo.sex = detail.sex ?? null;
  userInfo.birthDate = formatUTCToLocalDate(detail.birthDate) || "";
  userInfo.country = detail.country || "";
  userInfo.nationality = detail.nationality || "";
  userInfo.household = detail.household || "";
  userInfo.qualification = detail.qualification || "";
  userInfo.areaCode = detail.areaCode || "";
  userInfo.mobile = detail.mobile || "";
  userInfo.phone = formatPhone(detail.mobile, detail.areaCode);
  userInfo.email = detail.email || "";
  userInfo.address = detail.address || "";
  userInfo.certificateType = detail.certificateType || "";
  userInfo.certificateNo = detail.certificateNo ? String(detail.certificateNo) : "";
  userInfo.photoFront = detail.photoFront || "";
  userInfo.photoReverse = detail.photoReverse || "";
  userInfo.profileUrl = detail.profileUrl || "";
  phoneForm.areaCode = getDefaultAreaCode();
};

const fillRegistrationInfo = (detail) => {
  registrationInfo.associationName = detail.associationName || "";
  registrationInfo.userType = detail.userType ?? null;
  registrationInfo.registerProject = detail.registerProject || "";
  registrationInfo.membershipCode = detail.membershipCode || "";
  registrationInfo.occupationalLevel = detail.occupationalLevel || "";
  registrationInfo.firstTime = detail.firstTime || "";
  registrationInfo.registrationTime = formatUTCToLocalDate(detail.registrationTime) || "";
  registrationInfo.registrationCode = detail.registrationCode ?? null;
  registrationInfo.associationCode = detail.associationCode || "";
  registrationInfo.notes = detail.notes || "";
  registrationInfo.resignStatusCode = detail.registrationCode ?? null;
};

const buildUpdatePayload = (partial) => {
  const detail = userDetail.value || {};
  const payload = {
    id: detail.id || user.value?.bizUserId,
    nickname: detail.nickname,
    username: user.value?.username || detail.username,
    tenantId: store.tenantId,
    ...partial,
  };
  const sanitized = {};
  Object.entries(payload).forEach(([key, value]) => {
    if (value !== undefined) {
      sanitized[key] = value;
    }
  });
  return sanitized;
};

const updateUserProfile = async (partial) => {
  const payload = buildUpdatePayload(partial);
  if (!payload.id) return false;
  const { code } = await UpdatePlatformUser(payload);
  return code === 0;
};

const fetchUserDetail = async () => {
  if (!user.value?.id || loadingUser.value) return;
  loadingUser.value = true;
  try {
    const { code, data } = await GetPlatformUserDetail({ id: user.value.bizUserId });
    if (code === 0 && data) {
      userDetail.value = data || {};
      fillUserInfo(data || {});
      fillRegistrationInfo(data || {});
    }
  } finally {
    loadingUser.value = false;
  }
};

const updateCareerStatus = async (newResignStatus) => {
  if (updateLoading.career) return;
  if (registrationInfo.resignStatusCode === newResignStatus) return;
  updateLoading.career = true;
  try {
    const success = await updateUserProfile({ registrationCode: newResignStatus });
    if (success) {
      registrationInfo.resignStatusCode = newResignStatus;
      if (userDetail.value) {
        userDetail.value.resignStatus = newResignStatus;
      }
      ElMessage.success(t("memberProfile.careerStatusUpdateSuccess"));
    }
  } catch (error) {
    console.log("更新生涯状态失败", error);
  } finally {
    updateLoading.career = false;
  }
};

const handleTabChange = (tabName) => {
  activeTab.value = tabName;
};

const openPhoneForm = () => {
  phoneForm.areaCode = getDefaultAreaCode();
  phoneForm.newPhone = "";
  phoneFormRef.value?.clearValidate();
  showPhoneForm.value = true;
};

const savePhone = async () => {
  const form = phoneFormRef.value;
  if (!form || updateLoading.phone) return;
  try {
    await form.validate();
  } catch (error) {
    console.log("表单验证失败", error);
    return;
  }
  updateLoading.phone = true;
  const newMobile = phoneForm.newPhone?.trim();
  const newAreaCode = activeAreaCode.value;
  try {
    const success = await updateUserProfile({
      mobile: newMobile,
      areaCode: newAreaCode,
    });
    if (success) {
      userInfo.mobile = newMobile;
      userInfo.areaCode = newAreaCode;
      userInfo.phone = formatPhone(newMobile, newAreaCode);
      if (userDetail.value) {
        userDetail.value.mobile = newMobile;
        userDetail.value.areaCode = newAreaCode;
      }
      phoneForm.areaCode = getDefaultAreaCode();
      showPhoneForm.value = false;
      phoneForm.newPhone = "";
      form.clearValidate();
      ElMessage.success(t("memberProfile.phoneUpdateSuccess"));
    }
  } catch (error) {
    console.log("更新手机号失败", error);
  } finally {
    updateLoading.phone = false;
  }
};

const cancelPhone = () => {
  showPhoneForm.value = false;
  phoneForm.areaCode = getDefaultAreaCode();
  phoneForm.newPhone = "";
  phoneFormRef.value?.clearValidate();
};

const saveEmail = async () => {
  const form = emailFormRef.value;
  if (!form || updateLoading.email) return;
  try {
    await form.validate();
  } catch (error) {
    console.log("表单验证失败", error);
    return;
  }
  updateLoading.email = true;
  const newEmail = emailForm.newEmail?.trim();
  try {
    const success = await updateUserProfile({ email: newEmail });
    if (success) {
      userInfo.email = newEmail;
      if (userDetail.value) {
        userDetail.value.email = newEmail;
      }
      showEmailForm.value = false;
      emailForm.newEmail = "";
      emailForm.confirmEmail = "";
      form.clearValidate();
      ElMessage.success(t("memberProfile.emailUpdateSuccess"));
    }
  } catch (error) {
    console.log("更新邮箱失败", error);
  } finally {
    updateLoading.email = false;
  }
};

const cancelEmail = () => {
  showEmailForm.value = false;
  emailForm.newEmail = "";
  emailForm.confirmEmail = "";
  emailFormRef.value?.clearValidate();
};

const saveAddress = async () => {
  const form = addressFormRef.value;
  if (!form || updateLoading.address) return;
  try {
    await form.validate();
  } catch (error) {
    console.log("表单验证失败", error);
    return;
  }
  updateLoading.address = true;
  const addressParts = [addressForm.province, addressForm.city, addressForm.detailAddress].filter(Boolean);
  const newAddress = addressParts.join(" ").trim();
  try {
    const success = await updateUserProfile({ address: newAddress });
    if (success) {
      userInfo.address = newAddress;
      if (userDetail.value) {
        userDetail.value.address = newAddress;
      }
      showAddressForm.value = false;
      addressForm.province = "";
      addressForm.city = "";
      addressForm.detailAddress = "";
      form.clearValidate();
      ElMessage.success(t("memberProfile.addressUpdateSuccess"));
    }
  } catch (error) {
    console.log("更新地址失败", error);
  } finally {
    updateLoading.address = false;
  }
};

const cancelAddress = () => {
  showAddressForm.value = false;
  addressForm.province = "";
  addressForm.city = "";
  addressForm.detailAddress = "";
  addressFormRef.value?.clearValidate();
};

watch(
  () => user.value?.id,
  (id) => {
    if (id) {
      fetchUserDetail();
    }
  },
  { immediate: true }
);

watch(
  () => addressForm.province,
  () => {
    addressForm.city = "";
  }
);
</script>

<style lang="less" scoped>
.profile-tabs {
  background: white;
  border-radius: 8px 8px 0 0;
  margin-bottom: 0;

  :deep(.el-tabs__nav-wrap) {
    padding: 0 20px;
  }

  :deep(.el-tabs__nav-wrap::after) {
    display: none;
  }

  :deep(.el-tabs__item) {
    font-size: 16px;
    font-weight: 500;
    padding: 0 20px;
  }

  :deep(.el-tabs__content) {
    display: none;
  }
}

.personal-info-content {
  border-radius: 0 0 8px 8px;
  padding: 0 20px;
  box-sizing: border-box;

  .avatar-section {
    display: flex;
    justify-content: center;

    .avatar-placeholder {
      width: 120px;
      height: 120px;
      border: 1px solid #ddd;
      border-radius: 8px;
      overflow: hidden;

      .avatar-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .mountain-bg {
        width: 100%;
        height: 100%;
        background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
        position: relative;

        .sun {
          position: absolute;
          top: 15px;
          left: 50%;
          transform: translateX(-50%);
          width: 20px;
          height: 20px;
          background: #fff;
          border-radius: 50%;
          box-shadow: 0 0 10px rgba(255, 255, 255, 0.8);
        }

        &::before {
          content: "";
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          height: 40%;
          background: linear-gradient(180deg, transparent 0%, #90caf9 100%);
          clip-path: polygon(0 100%,
              20% 60%,
              40% 80%,
              60% 40%,
              80% 70%,
              100% 50%,
              100% 100%);
        }
      }
    }
  }

  .info-content {
    .info-section {
      .info-item {
        display: flex;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;

        &.editable {
          justify-content: space-between;
        }

        &:last-child {
          border-bottom: none;
        }

        .label {
          font-weight: 500;
          color: #666;
          min-width: 120px;
          margin-right: 15px;
        }

        .value {
          color: #333;
          flex: 1;
        }

        .modify-btn {
          color: #409eff;
          padding: 0;
        }
      }
    }

    .id-photos {
      display: flex;
      gap: 10px;

      .photo-placeholder {
        width: 120px;
        height: 80px;
        border: 1px solid #ddd;
        border-radius: 4px;
        overflow: hidden;

        .id-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .mountain-bg {
          width: 100%;
          height: 100%;
          background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
          position: relative;

          .sun {
            position: absolute;
            top: 10px;
            left: 50%;
            transform: translateX(-50%);
            width: 15px;
            height: 15px;
            background: #fff;
            border-radius: 50%;
            box-shadow: 0 0 8px rgba(255, 255, 255, 0.8);
          }

          &::before {
            content: "";
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 35%;
            background: linear-gradient(180deg, transparent 0%, #90caf9 100%);
            clip-path: polygon(0 100%,
                20% 60%,
                40% 80%,
                60% 40%,
                80% 70%,
                100% 50%,
                100% 100%);
          }
        }
      }
    }
  }
}

.registration-info-content {
  border-radius: 0 0 8px 8px;
  padding: 0 20px;
  box-sizing: border-box;

  .registration-list {
    .registration-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .label {
        font-weight: 500;
        color: #666;
        min-width: 150px;
        margin-right: 15px;
      }

      .value {
        color: #333;
        flex: 1;

        .el-button {
          color: #409eff;
          font-weight: normal;
          padding: 0;

          &.active {
            color: #409eff;
            font-weight: bold;
          }
        }
      }
    }
  }
}

:deep(.el-divider) {
  margin: 15px 0;
}

:deep(.full-width-item .el-form-item__content) {
  width: 100%;
}

.address-row {
  display: flex;
  width: 100%;
  align-items: center;
}

.address-select-item {
  flex: 1;
  margin-bottom: 0;
}

.address-select {
  width: 100%;
}

.address-gap {
  width: 12px;
  flex-shrink: 0;
}
</style>
